package com.sip.comadapter.communication;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import com.sip.comadapter.executor.common.ExecutionManager;
import com.sip.comserver.communication.CommunicationMessage;
import com.sip.comserver.communication.ConnectionThread;
import com.sip.comserver.communication.JobListner;

public class CommunicationManager extends JobListner {

	public CommunicationManager() throws IOException {
		
		super();
		// TODO Auto-generated constructor stub
		
		
	}
	
	public void startListen() throws Exception{
		
		while (true) {
			
			if (this.hasJob()) {

				final List<ConnectionThread> connectionList =new CopyOnWriteArrayList<ConnectionThread>(this.getConnectionList());
				synchronized (connectionList) {
					
					for (final ConnectionThread connectionThread : connectionList) {
						
						//Pick a connection to proceed.
						proceed(connectionThread);
					}
					
				}
			}
		}
	}
	
	private void proceed(final ConnectionThread connectionThread) throws Exception{
		
		pick(connectionThread);
		
		final CommunicationMessage message = recieveMessage(connectionThread);
		
		final ExecutionManager router =new ExecutionManager(message);
		final CommunicationMessage returnMessage = router.route();
		
		sendMessage(connectionThread, returnMessage);
		
		clear();
	}

}
